<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="举报类型" prop="reportType">
        <el-select v-model="queryParams.reportType" placeholder="请选择类型" clearable>
          <el-option label="用户举报" value="user" />
          <el-option label="内容举报" value="content" />
          <el-option label="评论举报" value="comment" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态" prop="processStatus">
        <el-select v-model="queryParams.processStatus" placeholder="请选择状态" clearable>
          <el-option label="待处理" :value="0" />
          <el-option label="处理中" :value="1" />
          <el-option label="已处理" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="举报人" prop="reporterUsername">
        <el-input
          v-model="queryParams.reporterUsername"
          placeholder="请输入举报人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="被举报人" prop="targetUsername">
        <el-input
          v-model="queryParams.targetUsername"
          placeholder="请输入被举报人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:reports:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:reports:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:reports:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:reports:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="reportsList" 
      @selection-change="handleSelectionChange"
      stripe
      border
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="reportId" width="80" />
      <el-table-column label="举报类型" align="center" prop="reportType" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.reportType === 'user'" type="warning" size="small">用户</el-tag>
          <el-tag v-else-if="scope.row.reportType === 'content'" type="primary" size="small">内容</el-tag>
          <el-tag v-else-if="scope.row.reportType === 'comment'" type="info" size="small">评论</el-tag>
          <span v-else>{{ scope.row.reportType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="举报原因" align="center" prop="reportReason" min-width="200" show-overflow-tooltip />
      <el-table-column label="举报人" align="center" min-width="120">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center;">
            <el-image
              v-if="scope.row.reporterAvatar"
              :src="scope.row.reporterAvatar"
              :preview-src-list="[scope.row.reporterAvatar]"
              style="width: 30px; height: 30px; border-radius: 50%; margin-right: 8px;"
              fit="cover"
            />
            <span>{{ scope.row.reporterUsername }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="被举报人" align="center" min-width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.targetUsername" style="display: flex; align-items: center;">
            <el-image
              v-if="scope.row.targetAvatar"
              :src="scope.row.targetAvatar"
              :preview-src-list="[scope.row.targetAvatar]"
              style="width: 30px; height: 30px; border-radius: 50%; margin-right: 8px;"
              fit="cover"
            />
            <span>{{ scope.row.targetUsername }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" align="center" prop="processStatus" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.processStatus === 0" type="warning" size="small">待处理</el-tag>
          <el-tag v-else-if="scope.row.processStatus === 1" type="primary" size="small">处理中</el-tag>
          <el-tag v-else-if="scope.row.processStatus === 2" type="success" size="small">已处理</el-tag>
          <el-tag v-else-if="scope.row.processStatus === 3" type="danger" size="small">已驳回</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="举报时间" align="center" prop="reportTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:reports:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:reports:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改举报投诉对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 举报信息 -->
          <el-tab-pane label="举报信息" name="report">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="举报类型" prop="reportType">
                  <el-select v-model="form.reportType" placeholder="请选择类型" style="width: 100%">
                    <el-option label="用户举报" value="user" />
                    <el-option label="内容举报" value="content" />
                    <el-option label="评论举报" value="comment" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="被举报对象ID" prop="targetId">
                  <el-input v-model="form.targetId" placeholder="请输入被举报对象ID" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="举报原因" prop="reportReason">
                  <el-input 
                    v-model="form.reportReason" 
                    type="textarea"
                    :rows="6"
                    placeholder="请输入举报原因"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="举报截图" prop="reportImages">
                  <image-upload 
                    v-model="form.reportImages" 
                    :limit="9"
                    :fileSize="5"
                    :isShowTip="true"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="举报地点" prop="reportLocation">
                  <el-input v-model="form.reportLocation" placeholder="请输入举报地点" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="举报时间" prop="reportTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.reportTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择举报时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 举报人信息 -->
          <el-tab-pane label="举报人信息" name="reporter">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="举报人ID" prop="reporterId">
                  <el-input v-model="form.reporterId" placeholder="请输入举报人ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="举报人用户名" prop="reporterUsername">
                  <el-input v-model="form.reporterUsername" placeholder="请输入举报人用户名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="举报人手机号" prop="reporterPhone">
                  <el-input v-model="form.reporterPhone" placeholder="请输入手机号" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="举报人头像" prop="reporterAvatar">
                  <image-upload 
                    v-model="form.reporterAvatar" 
                    :limit="1"
                    :fileSize="2"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 被举报人信息 -->
          <el-tab-pane label="被举报人信息" name="target">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="被举报人ID" prop="targetUserId">
                  <el-input v-model="form.targetUserId" placeholder="请输入被举报人ID" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="被举报人用户名" prop="targetUsername">
                  <el-input v-model="form.targetUsername" placeholder="请输入被举报人用户名" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="被举报人头像" prop="targetAvatar">
                  <image-upload 
                    v-model="form.targetAvatar" 
                    :limit="1"
                    :fileSize="2"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 处理信息 -->
          <el-tab-pane label="处理信息" name="process">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="处理状态" prop="processStatus">
                  <el-select v-model="form.processStatus" placeholder="请选择状态" style="width: 100%">
                    <el-option label="待处理" :value="0" />
                    <el-option label="处理中" :value="1" />
                    <el-option label="已处理" :value="2" />
                    <el-option label="已驳回" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="处理时间" prop="processTime">
                  <el-date-picker clearable style="width: 100%"
                    v-model="form.processTime"
                    type="datetime"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    placeholder="请选择处理时间">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="处理结果" prop="processResult">
                  <el-input 
                    v-model="form.processResult" 
                    type="textarea"
                    :rows="4"
                    placeholder="请输入处理结果"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="处理人ID" prop="processorId">
                  <el-input v-model="form.processorId" placeholder="请输入处理人ID" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <!-- 扩展信息 -->
          <el-tab-pane label="扩展信息" name="extra">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="举报分类" prop="reportCategory">
                  <el-input 
                    v-model="form.reportCategory" 
                    type="textarea" 
                    :rows="3"
                    placeholder='请输入JSON格式，例如：["违规内容","虚假信息"]'
                  />
                  <span class="form-tip">* 请输入合法的JSON数组格式</span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="举报状态" prop="status">
                  <el-input 
                    v-model="form.status" 
                    type="textarea" 
                    :rows="3"
                    placeholder='请输入JSON格式'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="扩展数据" prop="extraData">
                  <el-input 
                    v-model="form.extraData" 
                    type="textarea"
                    :rows="5"
                    placeholder='请输入JSON格式的扩展数据'
                  />
                  <span class="form-tip">* 请输入合法的JSON格式数据</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReports, getReports, delReports, addReports, updateReports } from "@/api/system/reports";
import ImageUpload from '@/components/ImageUpload';

export default {
  name: "Reports",
  components: {
    ImageUpload
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      reportsList: [],
      title: "",
      open: false,
      activeTab: 'report',
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reportType: null,
        targetId: null,
        reportReason: null,
        reportImages: null,
        reportCategory: null,
        reportTags: null,
        reportLocation: null,
        reportCoordinates: null,
        reportTime: null,
        reporterId: null,
        reporterPhone: null,
        reporterUsername: null,
        reporterAvatar: null,
        targetUserId: null,
        targetUsername: null,
        targetAvatar: null,
        processStatus: null,
        processResult: null,
        processTime: null,
        processorId: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      },
      form: {},
      rules: {
        reportType: [
          { required: true, message: "举报类型不能为空", trigger: "change" }
        ],
        targetId: [
          { required: true, message: "被举报对象ID不能为空", trigger: "blur" }
        ],
        reportReason: [
          { required: true, message: "举报原因不能为空", trigger: "blur" }
        ],
        reporterId: [
          { required: true, message: "举报人用户ID不能为空", trigger: "blur" }
        ],
        reporterUsername: [
          { required: true, message: "举报人用户名不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listReports(this.queryParams).then(response => {
        this.reportsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        reportId: null,
        reportType: null,
        targetId: null,
        reportReason: null,
        reportImages: null,
        reportCategory: null,
        reportTags: null,
        reportLocation: null,
        reportCoordinates: null,
        reportTime: null,
        reporterId: null,
        reporterPhone: null,
        reporterUsername: null,
        reporterAvatar: null,
        targetUserId: null,
        targetUsername: null,
        targetAvatar: null,
        processStatus: 0,
        processResult: null,
        processTime: null,
        processorId: null,
        status: null,
        extraData: null,
        createdAt: null,
        updatedAt: null
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reportId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset();
      this.activeTab = 'report';
      this.open = true;
      this.title = "添加举报投诉";
    },
    handleUpdate(row) {
      this.reset();
      this.activeTab = 'report';
      const reportId = row.reportId || this.ids
      getReports(reportId).then(response => {
        this.form = response.data;
        
        // 处理图片字段
        if (this.form.reportImages) {
          const urls = typeof this.form.reportImages === 'string' 
            ? JSON.parse(this.form.reportImages) 
            : this.form.reportImages;
          this.form.reportImages = Array.isArray(urls) ? urls.join(',') : urls;
        }
        
        // 处理JSON字段
        const jsonFields = ['reportCategory', 'reportTags', 'status', 'extraData'];
        for (const field of jsonFields) {
          if (this.form[field] && typeof this.form[field] === 'object') {
            this.form[field] = JSON.stringify(this.form[field], null, 2);
          }
        }
        
        this.open = true;
        this.title = "修改举报投诉";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const submitForm = JSON.parse(JSON.stringify(this.form));
          
          // 处理图片字段
          if (submitForm.reportImages && typeof submitForm.reportImages === 'string') {
            const urlArray = submitForm.reportImages.split(',').filter(url => url.trim());
            submitForm.reportImages = urlArray.length > 0 ? JSON.stringify(urlArray) : null;
          }
          
          // 处理JSON字段
          const jsonFields = ['reportCategory', 'reportTags', 'status', 'extraData'];
          for (const field of jsonFields) {
            if (submitForm[field] && typeof submitForm[field] === 'string') {
              try {
                submitForm[field] = submitForm[field].trim() 
                  ? JSON.parse(submitForm[field]) 
                  : null;
              } catch (e) {
                this.$modal.msgError(`${field}字段JSON格式不正确`);
                return;
              }
            }
          }
          
          if (submitForm.reportId != null) {
            updateReports(submitForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReports(submitForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      const reportIds = row.reportId || this.ids;
      this.$modal.confirm('是否确认删除举报投诉编号为"' + reportIds + '"的数据项？').then(function() {
        return delReports(reportIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('system/reports/export', {
        ...this.queryParams
      }, `reports_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
  display: block;
}

::v-deep .el-tabs--border-card {
  box-shadow: none;
}

::v-deep .el-tabs__content {
  padding: 20px;
}
</style>
